<template>
  <div style="display: flex; align-items: baseline">
    <el-upload
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      class="avatar-uploader"
      action="#"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
    <el-button style="margin-left: 20px;position: relative;top: -10px;" type="danger" icon="el-icon-delete" circle @click="del()" />
  </div>
</template>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: auto;
  display: block;
}
</style>

<script>
import axios from 'axios'
export default {
  data() {
    return {
      imageUrl: '',
      imageId: ''
    }
  },
  created() {
    this.imageUrl = this.$attrs.imageUrl
    console.log(this.imageUrl)
  },
  methods: {
    del() {
      this.imageUrl = ''
      this.$emit('url', '')
    },

    handleAvatarSuccess(res, file) {
      console.log(res)
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const loading = this.$loading({
        lock: true,
        text: '图片上传中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      const that = this
      var formData = new FormData()
      formData.append('files', file)
      // 上传图片地址
      // const url = process.env.VUE_APP_BASE_API + '/fileoss/oss'
      const alyUrl = 'https://www.fengshu.press/fileoss/oss'// 上传阿里云 的地址

      const resArr = []

      resArr[0] = axios.post(alyUrl, formData).then(res => {
        res = res.data
        const url = res.data.url
        console.log(url)
        return { imageUrl: url }
      })

      const eayArUrl = 'https://www.fengshu.press/easyarservice/shibietu/upload'// 上传阿里云 的地址

      resArr[1] = axios.post(eayArUrl, formData).then(res => {
        console.log(res)
        return { targetId: res.data.data.targetId }
      })
      Promise.all(resArr).then(res => {
        loading.close()
        const obj = { ...res[0], ...res[1] }
        console.log(obj)

        if (obj.targetId) {
          that.imageUrl = obj.imageUrl
          that.$emit('oncheng', { url: obj.imageUrl, id: obj.targetId })
        } else {
          that.$message.warning('识别图上传失败')
        }
        // that.imageUrl = url

        console.log(res)
      })

      return false
    }
  }
}
</script>
